<template>
    <view class="flex-col flex-center w-full">
        <view class="flex justify-start flex-wrap gap-x-4 gap-y-2 p-4 w-full box-border">
            <text class="text-sm text-gray-500" v-if="myTag.length === 0">暂无标签</text>
            <nut-tag v-for="item in myTag" :key="item.id" closeable type="success" @close="onRemove(item)"> {{item.tagName}} </nut-tag>
        </view>
        <nut-popup v-model:visible="show" position="bottom">
            <tags class="w-full" @addTag="onAddTag"/>
            <view class="flex-center m-4 gap-x-8">
            <nut-button type="default" @click="show = false">关 闭</nut-button>
            <!-- <nut-button type="success" @click="show = false">确定添加</nut-button> -->
            </view>
        </nut-popup>
        <view class="fixed bottom-4 w-full p-4 box-border">
            <nut-button class="!w-full" type="success" @click="show = true">添加标签</nut-button>
        </view>
    </view>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import tags from './components/tags.vue';
import { request } from '@/service/request';
import { useAuthStore } from '@/store';
import Taro from '@tarojs/taro';

const userStore = useAuthStore();

const myTag = ref<any[]>([]);

const show = ref(false);

onMounted(() => {
    getTagList();
})

const getTagList = () => {
    request.get('/health_records/health_recordtag/healthRecordTagInfo/list', {
        name: userStore.nurseUser.name,
    }, {
        useErrMsg: true
    }).then((res:any) => {
        console.log("res==== my tag", res)
        myTag.value = res.success?.records || [];
    })
}   

const onAddTag = (item: any) => {
    console.log("item==== add tag ===", item)
    if(myTag.value.find((tag) => tag.tagId === item.id)) {
        Taro.showToast({
            title: '标签已存在',
            icon: 'none'
        })
        return;
    }
    // myTag.value.push(item);
    request.post('/health_records/health_recordtag/healthRecordTagInfo/add', {
        name: userStore.nurseUser.name,
        tagId: item.id,
        tagName: item.name,
    }, {
        useErrMsg: true
    }).then((res:any) => {
        console.log("res==== add tag", res)
        getTagList();
    })
    // show.value = false;
}

const onRemove = (item: any) => {
    // myTag.value = myTag.value.filter((tag) => tag.id !== item.id);
    request.delete('/health_records/health_recordtag/healthRecordTagInfo/delete?id=' + item.id, {
        // id: item.id,
    }, {
        useErrMsg: true
    }).then((res:any) => {
        console.log("res==== delete tag", res)
        getTagList();
    })
}

</script>
<style lang="scss">
.nut-tag {
    font-size: 14px;
    padding: 4px 8px;
}
</style>